const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();

// 使用 body-parser 解析 JSON 请求体
app.use(bodyParser.json({ limit: '50mb' }));

// 上传接口
app.post('/upload', async (req, res) => {
  try {
    const { uploadFiles } = req.body; // 提取字段 uploadFiles

    if (!Array.isArray(uploadFiles)) {
      return res.status(400).send('Invalid data format. Expected array of binary files.');
    }

    // 保存每个文件
    uploadFiles.forEach((fileBuffer, index) => {
      const buffer = Buffer.from(new Uint8Array(fileBuffer.data)); // 转换为 Buffer
      const filePath = path.join(__dirname, `uploads/file_${index + 1}.bin`);
      fs.writeFileSync(filePath, buffer);
      console.log(`File saved: ${filePath}`);
    });

    res.status(200).send({ message: 'Files uploaded successfully!' });
  } catch (error) {
    console.error('Error handling upload:', error);
    res.status(500).send('Error processing files');
  }
});

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
